<?php
namespace Easy;

class Easy
{

    const RUN_MODEL_NAMESPACE = 1;
    const RUN_MODEL_FULLNESS  = 2;

    private static $model;
    private static $scriptPHP;

    private static $_instance = [];

    public static function start($model = self::RUN_MODEL_NAMESPACE, $scriptPHP = [],$func=null)
    {
        self::registAutoLoad($model, $scriptPHP);
        if($func){
            $func();
        }
        switch ($model) {
            case self::RUN_MODEL_FULLNESS:
                self::startByFullness();
                break;
            default:
                self::startByNameSpace();
        }
    }

    public static function registAutoLoad($model, $scriptPHP = [])
    {
        self::$scriptPHP = $scriptPHP;
        self::$model     = $model;
        spl_autoload_register('Easy\Easy::autoload');
        LoadClass::loadCoreFile();
        if ($scriptPHP) {
            LoadClass::initClsHash($scriptPHP);
        }
    }

    private static function startByNameSpace()
    {
        if (FRAME_AUTO_RUN) {
            $apiArray = Router::dispatchByNamespace();
            self::run($apiArray);
        }
    }

    private static function startByFullness()
    {
        if (FRAME_AUTO_RUN) {
            $apiArray = Router::dispatchByFullness();
            self::run($apiArray);
        }
    }

    public static function run($apiArray)
    {
        $class      = $apiArray['class'];
        $method     = $apiArray['method'];
        $Controller = new $class;
        $Controller->$method();
    }

    public static function autoload($class)
    {
        if (class_exists($class)) {
            return;
        }
        switch (self::$model) {
            case self::RUN_MODEL_FULLNESS:
                return LoadClass::loadByPathHash($class, self::$scriptPHP);
            case self::RUN_MODEL_NAMESPACE:
                return LoadClass::loadByNamespace($class);
        }

        return null;
    }

    static public function instance($class, $method = '')
    {
        $identify = $class . $method;
        if (!isset(self::$_instance[$identify])) {
            if (class_exists($class)) {
                $o = new $class();
                if (!empty($method) && method_exists($o, $method)) {
                    self::$_instance[$identify] = call_user_func([&$o, $method]);
                } else {
                    self::$_instance[$identify] = $o;
                }
            } else {
                E('_CLASS_NOT_EXIST_:' . $class);
            }
        }

        return self::$_instance[$identify];
    }
}
